package com.wechat.common.interceptor.core;

import com.wechat.common.security.context.UserInfoContext;
import com.wechat.common.security.token.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {

    private final TokenUtil tokenUtil;

    public UserInfoInterceptor(TokenUtil tokenUtil) {
        this.tokenUtil = tokenUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader("token");
        // 检查请求头中是否包含JWT令牌
        if (header == null || !header.startsWith("Bearer ")) {
            // 未提供令牌
            return true;
        }
        // 提取JWT令牌（去除Bearer前缀）
        String token = header.substring(7);
        try {
            if (tokenUtil.validateToken(token)) {
                Long userId = tokenUtil.getUserIdFromToken(token);
                log.debug("当前登录用户 {}", userId);
                UserInfoContext.setUserId(userId);
            }
            return true;
        } catch (Exception ignore) {
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfoContext.removeUserId();
    }
}
